<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      #canvas {
        border: 1px solid;
      }
    </style>
  </head>

  <body>
    <canvas width="400" height="400" id="canvas"> 请升级你的服务器 </canvas>
    <script>
      var canvas = document.querySelector("#canvas");
      var context = canvas.getContext("2d");
      function Ball(x, y, r, color, dx, dy, dr, opcity) {
        this.x = x;
        this.y = y;
        this.r = r;
        this.color = color;
        this.dx = dx;
        this.dy = dy;
        this.dr = dr;
        this.opcity = opcity;
      }
      Ball.prototype.init = function () {
        if (this.r <= 0) return;
        context.beginPath();
        context.fillStyle = this.color;
        context.globalAlpha = this.opcity;
        context.arc(this.x + this.dx, this.y + this.dy, this.r + this.dr, 0, 7);
        context.fill();
      };
      var timer = 0;
      // function getBallList
      function getBallList(x, y, r) {
        var list = [];
        for (let i = 0; i < 20; i++) {
          let arr = [];
          let color = `rgb(${Math.floor(Math.random() * 255)},${Math.floor(
            Math.random() * 255
          )},${Math.floor(Math.random() * 255)})`;
          let signX = Math.random() > 0.5 ? 1 : -1;
          let signY = Math.random() > 0.5 ? 1 : -1;
          let dx = Math.floor(Math.random() * 5 * signX);
          let dy = Math.floor(Math.random() * 5 * signY);
          let opcity = Math.random();
          let dr = Math.random();
          arr.push(x);
          arr.push(y);
          arr.push(r);
          arr.push(color);
          arr.push(dx);
          arr.push(dy);
          arr.push(dr);
          arr.push(opcity);
          list.push(arr);
        }
        return list;
      }
      function ballRun(event) {
        clearInterval(timer);
        var x = event.offsetX;
        var y = event.offsetY;
        var r = 20;
        var list = getBallList(x, y, r);
        list.forEach((item, index) => {
          var ball = new Ball(...item);
          ball.init();
        });
        timer = setInterval(() => {
          list.map((item) => {
            item[0] += item[4];
            item[1] += item[5];
            item[2] -= item[6];
            return item;
          });
          context.clearRect(0, 0, 400, 400);
          list.forEach((item, index) => {
            var ball = new Ball(...item);
            ball.init();
          });
        }, 30);
      }
      canvas.onclick = function (event) {
        ballRun(event);
      };
      canvas.onmousedown = function (event) {
        ballRun(event);
        canvas.onmousemove = function (e) {
          ballRun(e);
          canvas.onmouseup = function () {
            canvas.onmousemove = null;
          };
        };
      };
    </script>
  </body>
</html>
